<template>
    <div class="task-page">
        <div>
            <van-nav-bar title="资产盘点任务" left-arrow @click-left="onClickLeft" />
        </div>
        <div>
            <tab :listData="listData" keytype="qb" @tab-change="onTabChange"></tab>
        </div>
        <div class="search-section"> 
            <vSearch @openpopup="openpopup" :showicon="true" @search="onSearch" @input="onSearchInput"></vSearch>
            <vPopup ref="popupRef"></vPopup>
        </div>
        <div class="task-list">
            <van-list
                v-model="loading"
                :finished="finished"
                finished-text="没有更多了"
                @load="onLoad"
            >
            <vCard 
                v-for="(task, index) in filteredTasks" 
                :key="task.id || index"
                :task="task"
                @edit="goEditTask"
                @start="goDitailTask"
                @terminate="terminateTask"
            />
            </van-list>
        </div>
    </div>
</template>
<script>
import tab from './components/tab.vue'
import vSearch from './components/vsearch.vue'
import vCard from './components/vCard.vue'
import vPopup from './components/vPopup.vue'
import backMixin from '../../mixins/backMixin'
export default {
    mixins: [backMixin],
    components: {
        tab,
        vCard,
        vSearch,
        vPopup
    },
    data() {
        return {
            currentTab: 'qb',
            searchKeyword: '',
            loading: false,
            finished: false,    
            pageNum: 1,
            pageSize: 20,
            listData: [
                { name: '全部', key: 'qb' },
                { name: '待盘点', key: 'dpd' },
                { name: '待复核', key: 'dfh' },
                { name: '已完成', key: 'ywc' },
                { name: '已终止', key: 'yzz' },
            ],
            tasks: [
        
            ],
             orgTree: null,
        }
    },
    computed: {
        filteredTasks() {
            return this.tasks
        }
    },
    mounted() {
      // 初次加载列表
      this.getListData()
      this.getorgTree()
    },
    activated() {
        // 当从编辑页返回（keep-alive 激活）时，检查刷新标志并刷新列表
        try {
            const flag = sessionStorage.getItem('taskRefresh')
            if (flag) {
                sessionStorage.removeItem('taskRefresh')
                this.refreshList()
            }
        } catch (e) {
            console.error('读取刷新标志失败:', e)
        }
    },
    methods: {
        onLoad(v) {
            console.log(this.finished,'finished')
         if ( this.finished) return
           
            console.log(this.loading,'loading')
         
                this.getListData()
                
          
        
        },
             async getorgTree() {
            try {
                const res = await this.$Geting(this.$api.getorgTree)
                if (res.code === '0') {
                    this.orgTree = res.data.treeData
                    this.$store.commit('assectData/setorgTree', this.orgTree)
                    console.log('组织树加载完成:', this.orgTree)
                } else {
                    this.$toast(res.message)
                }
            } catch (err) {
                console.error('获取管理单位树出错', err)
            }
        },
        onClickLeft() {
            this.$router.back()
        },
        onTabChange(tabKey) {
            console.log(tabKey, 'tabKey')
            
            this.currentTab = tabKey
            this.pageNum = 1
            this.tasks = []
            if(tabKey === 'qb'){
                this.getListData()
            }
            if(tabKey === 'dpd'){
                this.getListData('',0)
            }else if(tabKey === 'dfh'){
                this.getListData('',1)
            }else if(tabKey === 'ywc'){
                this.getListData('',2)
            }else if(tabKey === 'yzz'){
                this.getListData('',3)
            }
        },
        onSearchInput(value) {
            console.log(value)
        },
        onSearch(value){
            console.log(value,'value')
            this.searchKeyword = value
            console.log(this.searchKeyword, 'searchKeyword')
            this.pageNum = 1
            this.tasks = []
            this.getListData(this.searchKeyword)
        },
     
        openpopup(v){
            if(v){
                this.$nextTick(()=>{
                this.$refs.popupRef.open()
            })
            }
        },
   
        // goPmdTask(v){
        //     console.log(v,'v')
        //     this.$router.push({ name: 'pmd', query: { k: v.sourceId } });
        // },
        goEditTask(v){
            this.$router.push({ name: 'editTask'});
            this.$store.commit('assectData/setAssectInfo', v) //盘点数据
            console.log(this.$store.state.assectData.assectInfo,'this.$store.state.assectData.assectInfo')
        },
        goDitailTask(v){
            this.$router.push({ name: 'detailTask',params:{id:v.id}});
        },
      async  terminateTask(task) {
            // 终止任务逻辑
            console.log('终止任务:', task)
            let data={closed:1}
            const res = await this.$Posting(this.$api.getupdateTask,data)
                console.log(res, 'res')
                if (res.code === '0' && res.data) {

                    this.$toast('操作成功')
                }else{
                    this.$toast(res.message)
                }
        },
        async getListData(keywords = '',status) {
            try {
                const data = {
                    pageNum: this.pageNum,
                    pageSize: this.pageSize,
                    query: {
                        currentNode: 0,
                        keywords: keywords,
                        orgId: "100005",
                        state:status
                    }
                }
                // if(status === 0 || status === 1 || status === 2 || status === 3){
                //     data.query.status = status
                // }
                this.loading = true
                const res = await this.$Posting(this.$api.getlistPage, data)
                console.log(res, 'res')
                if (res.code === '0' && res.data) {
                    const newAssets = res.data.list || [];
                    if (newAssets.length > 0) {
                        const existingTaskNos = new Set(this.tasks.map(t => t.taskNo));
                        const filteredAssets = newAssets.filter(item => !existingTaskNos.has(item.taskNo));
                        this.tasks = [...this.tasks, ...filteredAssets];
                        console.log(this.tasks, 'task');
                        this.pageNum++;
                        this.loading=false
                    } else {
                        this.loading=false
                        this.finished = true;
                        console.log(this.finished,'finiihj')
                    }
                }
                console.log(res)
            } catch (error) {
                console.error('加载数据失败:', error)
                // 默认数据 用于测试
                const defaultTasks = [
                    {
                        taskNo: 'PD2024060001',
                        orgName: '默认机构',
                        beginDate: Date.now(),
                        endDate: Date.now() + 7 * 24 * 3600 * 1000,
                        propertyAmount: 15,
                        stocktakingAmount: 0
                    }
                ]
                this.tasks = [...this.tasks, ...defaultTasks]
                this.loading=false
                this.finished = true
            }

            
        }
        ,
        // 刷新列表（通常在编辑成功后返回时调用）
        refreshList() {
            this.pageNum = 1
            this.finished = false
            this.loading = false
            this.tasks = []
            this.getListData()
        }
    }
}
</script>

<style scoped>
.task-page {
    background-color: #f5f5f5;
    min-height: 100vh;
}

.search-section {
    padding: 10px 15px;
    background-color: #fff;
}

.task-list {
    padding: 10px 0px;
    height: 78vh;
    overflow-y: auto;
}
</style>